package com.ls.fw.mvc.springmvc.support.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.ls.fw.commons.core.utils.string.StringUtils;
import com.ls.fw.mvc.springmvc.constant.Global;
import com.ls.fw.web.core.servlet.utils.UserAgentUtils;

/**
 * 手机端视图拦截器
 */
public class MobileInterceptor extends BaseInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
			ModelAndView modelAndView) throws Exception {
		if (open && modelAndView != null){
			// 如果是手机或平板访问的话，则跳转到手机视图页面。
			if(UserAgentUtils.isMobileOrTablet(request) && !StringUtils.startsWithIgnoreCase(modelAndView.getViewName(), "redirect:")){
				if(modelAndView.hasView() && modelAndView.isReference()){
					String view = modelAndView.getViewName();
					if(org.apache.commons.lang3.StringUtils.isNotBlank(view)){
						String mobile = Global.getMobilePath();
						if(org.apache.commons.lang3.StringUtils.isNotBlank(mobile)){
							modelAndView.setViewName(mobile+"/" + view);
						}
					}
				}
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
		
	}
}
